#include <stdio.h>
#include <stdlib.h>

#include "htlog.h"

int htlogflg;
FILE * logfile;
int errcode;
char errmsg[256];

int htlog_init(char * fn)
{
  if(!(logfile = fopen(fn, "a+")))
    {
      printf("Error while initialize log, cannot open log file %s\n", fn);
      return 0;
    }
  
  return 1;
  
}

void htlog(char * fn, int ln, char * msg,...)
{
  va_list args;
  char buf[1024*5];
  int len, msglen;
  
  len = snprintf(buf, sizeof(buf), "%s(%d):", fn, ln);
  if(len<0)
    {
      /*error*/
      return;
    }
  else if(len>=sizeof(buf))
    {
      /*merely happen, file name and line number has length more than sizeof(buf), write first*/
      fwrite(buf, sizeof(buf), 1, logfile);
      len = 0;
    }
  
  va_start(args, msg);
  msglen = vsnprintf(&buf[len], sizeof(buf)-len, msg, args);
  va_end(args);
  
  if(msglen<0)
    {
      /*error*/
      return;
    }
  else if(msglen>=sizeof(buf)-len)
    {
      len = sizeof(buf);
    }else
    {
      len += msglen+1;
    }
  buf[len-1] = '\n';
  
  fwrite( buf, len, 1, logfile);
  fflush(logfile);
  
  return;
  
}

